package com.ushine.web.component.design.chain.factory;

import com.ushine.web.component.design.chain.config.ApplicationContextHelper;
import com.ushine.web.component.design.chain.config.ChainBaseParams;
import com.ushine.web.component.design.chain.handler.AbstractChainTemplateHandler;

import java.util.Comparator;
import java.util.List;

/**
 * @Author: yls
 * @Date: 2021/12/24 13:39
 * @Description: 父级责任链工厂
 * @Version 1.0
 */
public abstract class AbstractChainTemplateFactory {

    /**
     * 功能描述:
     * 〈初始化过滤链〉
     *
     * @param abstractChainTemplateHandlers 责任链集合
     * @return : void
     * @author : yls
     * @date : 2022/03/04 11:14
     */
    protected static void initGatewayHandles(List<AbstractChainTemplateHandler<ChainBaseParams>> abstractChainTemplateHandlers) {
        abstractChainTemplateHandlers.sort(Comparator.comparing(AbstractChainTemplateHandler::getOrder, Integer::compareTo));
        int size = abstractChainTemplateHandlers.size();
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                abstractChainTemplateHandlers.get(i).setAbstractChainTemplateHandler(null);
            } else {
                abstractChainTemplateHandlers.get(i).setAbstractChainTemplateHandler(abstractChainTemplateHandlers.get(i + 1));
            }

        }
    }

    /**
     * 功能描述:
     * 〈利用反射创建对象，设置属性值〉
     *
     * @param applicationContextHelper 获取bean
     * @param aClass                   类型
     * @param order                    排序
     * @param templateHandlers         模板处理器集合
     * @return : void
     * @author : yls
     * @date : 2022/02/24 13:44
     */
    protected void creteGatewayHandle(ApplicationContextHelper applicationContextHelper, Class<? extends AbstractChainTemplateHandler> aClass,
                                      int order, List<AbstractChainTemplateHandler<ChainBaseParams>> templateHandlers) {
        // 调用构造方法，获取对象
        AbstractChainTemplateHandler abstractChainTemplateHandler = applicationContextHelper.popBean(aClass);
        if (abstractChainTemplateHandler == null) {
            return;
        }
        abstractChainTemplateHandler.setOrder(order);
        // 添加过滤链
        templateHandlers.add(abstractChainTemplateHandler);
    }
}
